<?php
/**
 * Created by PhpStorm.
 * User: zhan
 * Date: 2018/5/25  10:57
 */
namespace app\admin\controller;
class Category extends Common
{
    private $table_admin;
    function __construct()
    {
        parent::__construct();
        $this->table_admin = db('category');
        $nav_result = db('nav')->field('id, name')->where('is_display=1')->order('order_number desc')->select();
        $this->assign('nav_result', $nav_result);
    }

    public function index()
    {
        $category_result = $this->table_admin->alias('c')->join('nav n', 'n.id=c.nav_id')->field('c.*,n.name as navname')->paginate();
//        halt($category_result);
        $page = $category_result->render();
        $this->assign('category_result', $category_result);
        $this->assign('page', $page);
        return $this->fetch('Category/lists');
    }

    //添加分类
    public function add()
    {
        if(request()->isAjax()){
            $nav_id = input('nav_id');
            $title = input('title');

            $data['nav_id'] = $nav_id;
            $data['name'] = $title;

            $where['name'] = array('like', $title);
            $where['nav_id'] = $nav_id;

            $name = $this->table_admin->where($where)->value('name');
            if($name){
                $this->error('该分类已存在');
            }

            $id = input('id');
            if($id){
               $bool = $this->table_admin->where('id='.$id)->update($data);
            }else{
                $bool = $this->table_admin->insert($data);
            }

            if($bool){
                return $this->success('操作成功', url('Category/index'));
            }else{
                return $this->error('操作失败');
            }
        }



        return $this->fetch();
    }

    //修改分类页面
    public function edit()
    {
        $id = input('id');
        $data = $this->table_admin->where('id='.$id)->find();
        $this->assign('data', $data);
        return $this->fetch();
    }

    //删除分类
    public function delete()
    {
        $id = input("id");
        if(!$id) $this->error('参数有误');
        $da=$this->table_admin->where("id='$id'")->find();
        if(!$da) $this->error('数据不存在');
        $res=$this->table_admin->where("id='$id'")->delete();
        if(!$res) $this->error('删除失败');
        $this->success("删除成功!",url('Article/index'));

    }
}